<template>
	<view class="content" >
        <u-navbar :fixed="true" :shadow="true" :safeAreaInsetTop="true" :placeholder="true"
            @leftClick="back" title="实名认证">
        </u-navbar>

        <!-- 专户统计 -->
        <view class="u-m-t-30 u-p-t-30 u-p-b-50 item">
            <view class="uni-area">
                <uni-item-base-plus :baseData="fohfTotal" @confirmSelect="confirmSelect" />
            </view>
        </view>

        <!-- 身份证验证 -->
        <view class="u-m-t-30 u-p-t-30 u-p-b-50 item">
            <view class="uni-area">
                <text class="u-font-32 font-bold">身份证验证</text>
                <view v-if="!id" class="u-m-t-30 u-flex u-row-between">
                    <!-- 身份证正面 -->
                    <u-upload
                        @afterRead="afterRead" @delete="deletePic"
                        name="front" deletable :multiple="true" :maxCount="1"
                        width="330rpx" height="208rpx" uploadText="请上传身份证正面">
                        <u--image v-if="identityCard.front" :src="identityCard.front" 
                            width="330rpx" height="208rpx" radius="8rpx">
                        </u--image>
                    </u-upload>
                    <u-upload
                        @afterRead="afterRead" @delete="deletePic"
                        name="back" deletable :multiple="true" :maxCount="1"
                        width="330rpx" height="208rpx" uploadText="请上传身份证反面">
                        <u--image v-if="identityCard.back" :src="identityCard.back" 
                            width="330rpx" height="208rpx" radius="8rpx">
                        </u--image>
                    </u-upload>
                </view>
                <uni-item-base-plus :baseData="identity" />
            </view>
        </view>

        <!-- 验证身份信息 -->
        <view v-if="!id" class="u-m-t-30 u-p-t-30 u-p-b-50 item">
            <view class="uni-area">
                <text class="u-font-32 font-bold">验证身份信息</text>
                <view class="u-m-t-30 u-flex u-flex-col">
                    <u--image :src="identityCard.photo?identityCard.photo:'/static/faceHead.png'" 
                        width="266rpx" height="280rpx" radius="6" @tap="face">
                    </u--image>
                    <text class="u-m-t-30 u-font-28 uni-dec-color">提示:点击图片前往人脸识别！</text>
                </view>
            </view>
        </view>


        <!-- 下一步 -->
        <view class="next-box u-flex u-row-center">
            <u-button class="next" type="primary" shape="circle" text="下一步" @tap="next"></u-button>
        </view>

        <!-- 提示组件 -->
        <u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
    import upload from '@/configs/uploadFile'
    // import face from '@/nativeplugins/AThree-Face'
    import {mapGetters,mapMutations} from 'vuex'
    import { pathToBase64 } from 'image-tools';
	export default {
		data() {
			return {
                userInfo: uni.getStorageSync('userInfo'),
                // 参数
                parameter:{ 
                    deptId: uni.getStorageSync("userInfo").deptId, 
                    gcbh: uni.getStorageSync("userInfo").ssgcbh
                },
                // 专户统计
                fohfTotal:{
                    line: false,
                    title: '专户统计',
                    rightText: '',
                    list:[
                        { show:true, required:true, title:'项目名称', value: uni.getStorageSync('userInfo').ssgcmc },
                        { show:true, required:true, title:'施工企业', value: uni.getStorageSync('userInfo').ssqymc },
                        { show:true, required:true, title:'所属企业', value:'', type:'select', pla:'请选择所属企业', data:[] },
                    ]
                },
                identityCard:{
                    front: '',
                    back: '',
                    photo: '',
                },
                // 身份证信息
                identity:{
                    line: false,
                    title: '',
                    rightText: '',
                    list:[
                        { show:true, required:true, title:'姓名', value:'请上传身份证正面' },
                        { show:true, required:true, title:'公民身份证号码', value:'请上传身份证正面' },
                    ]
                },
                // 修改时的业务Id
                id: null, 
			}
		},

        onReady(){},

        computed: {
            ...mapGetters(['autonymSubmitData']),
        },

		onLoad(option) {
            // this.getTest()
            if( option.id ) { // 修改
                this.id = option.id
                this.getDetails()
            }else{ // 新增
                const data1 = {
                    gcmc: this.userInfo.ssgcmc,
                    gcbh: this.userInfo.ssgcbh,
                }
                this.setAutonymSubmitData(data1)
            }
            // 所属企业
            this.getEntList()
        },

        onShow(){
            this.identityCard.photo = this.autonymSubmitData.photo 
        },


		methods: {
            ...mapMutations(['setAutonymSubmitData']),

            // 返回
            back(){
                uni.navigateBack()
            },

            // 详情
            getDetails(){
                this.$request(this,this.$apis.autonymDetail,{id:this.id}).then(res=>{
                    // console.log('详情',res)
                    this.setAutonymSubmitData(res)
                    // 回填所属企业
                    this.fohfTotal.list[2].value = res.qymc
                    // 回填身份信息
                    this.identity.list[0].value = res.xm
                    this.identity.list[1].value = res.zjhm
                }).then()
            },
            

            // 所属企业
            getEntList(){
                this.$request(this,this.$apis.belongEntList,this.parameter).then(res=>{
                    // console.log('所属企业',res)
                    res.map((v,i)=>{
                        this.fohfTotal.list[2].data.push({ 
                            label: v.qymc, 
                            value: v.qybm, 
                            deptName: v.deptName,
                            deptId: v.deptId,
                            districtName: v.districtName,
                            districtId: v.districtId
                        })
                    })
                }).then()
            },
            // 选择所属企业
            confirmSelect(e){
                this.fohfTotal.list[2].value = e.label
                const data2 = {
                    qymc: e.label, // 所属企业名称
                    qybm: e.value, // 所属企业
                    deptName: e.deptName, // 所属部门名称
                    deptId: e.deptId, // 所属部门
                    districtName: e.districtName, // 所属区划名称
                    districtId: e.districtId // 所属区划
                }
                this.setAutonymSubmitData(data2)
            },


            // 新增图片
            afterRead(event) {
                uni.showLoading({ title:'上传中' })
                pathToBase64(event.file[0].url).then(res=>{
                    this.getOCRsignature(event.name,event.file[0].url,res)
                }).catch(err=>{})
            },
            // 身份证识别 https://cloud.tencent.com/document/api/866/33524
            getOCRsignature(face,path,ImageBase64){
                this.$request(this,this.$apis.ocrSignature,{ImageBase64:ImageBase64}).then(res=>{
                    uni.showLoading({ title:'识别中' })
                    uni.request({
                        url: 'https://ocr.tencentcloudapi.com',
                        method: 'POST',
                        data:{
                            ImageBase64: ImageBase64
                        },
                        header: {
                            'X-TC-Action': 'IDCardOCR',
                            'X-TC-Version': '2018-11-19',
                            'X-TC-Region': 'ap-beijing',
                            'X-TC-Timestamp': res.timestamp,
                            'Content-Type': 'application/json; charset=utf-8',
                            'Authorization': res.data,
                        },
                        success: e => {
                            uni.hideLoading()
                            if( e.data.Response.Error ){
                                uni.$u.toast('证件识别失败')
                            }else{
                                const result = e.data.Response
                                if( face == 'front' ){
                                    if( result.Name ){ // 后端签名应该没做正反面的区别,故只有再这里判断
                                        this.autonymVerifyIdcard(path,ImageBase64,result)
                                    } else{
                                        uni.$u.toast('请上传清晰正确的身份证正面照片')
                                    }
                                }else{
                                    if( result.Authority ){
                                        this.identityCard.back = ImageBase64
                                        const data4 = {
                                            qfjg: result.Authority, // 签发机关
                                            yxksrq: this.$moment(result.ValidDate.split('-')[0]).format('YYYY-MM-DD'), // 有效期开始日期
                                            yxjsrq: this.$moment(result.ValidDate.split('-')[1]).format('YYYY-MM-DD'), // 有效期结束日期
                                            back: ImageBase64, // 身份证反面
                                            __back: path,
                                        }
                                        this.setAutonymSubmitData(data4)
                                    }else{
                                        uni.$u.toast('请上传清晰正确的身份证反面照片')
                                    }
                                }
                            }
                        },
                        fail: e => {
                            uni.hideLoading()
                            uni.$u.toast('证件识别失败')
                        }
                    });
                }).then()
            },
            // 验证身份证是否已经存在
            autonymVerifyIdcard(path,ImageBase64,result){
                uni.showLoading({ title:'检测中'})
                const parameter = { 
                    zjhm: result.IdNum, 
                    gcbh: this.parameter.gcbh
                }
                this.$request(this,this.$apis.autonymVerifyIdcard,parameter).then(res=>{
                    if( res.code == 200 ){
                        this.identityCard.front = ImageBase64
                        this.identity.list[0].value = result.Name
                        this.identity.list[1].value = result.IdNum
                        const data3 = {
                            xm: result.Name, // 姓名
                            zjhm: result.IdNum, // 证件号码
                            csrq: this.$moment(result.Birth).format('YYYY-MM-DD'), // 出生日期
                            xb: result.Sex, // 性别
                            mz: result.Nation+'族', // 民族
                            jiGuan: '', // 籍贯[非必填]
                            hjszd: result.Address, // 住址
                            front: ImageBase64, // 身份证正面
                            __front: path 
                        }
                        this.setAutonymSubmitData(data3)
                        // 根据证件号码查询基本信息
                        this.getZjhmInfo()
                    }else{
                        uni.$u.toast(res.msg)
                    }
                })
            },
            // 根据证件号码查询基本信息
            getZjhmInfo(){
                const api = JSON.parse(JSON.stringify(this.$apis.zjhmInfo))
                api.url+=this.autonymSubmitData.zjhm
                this.$request(this,api,{}).then(res=>{
                    // console.log('基本信息',res)
                })
            },
            // 删除图片
			deletePic(event) {},


            // 人脸识别
            face(){
                if( !this.id ){
                    if( this.identityCard.front && this.identityCard.back ){
                        uni.navigateTo({ url: '/pages/common/face' })
                    }else{
                        uni.$u.toast('请上传身份证照片')
                    }
                }else{
                    uni.$u.toast('修改实名认证不需要重新进行人脸识别')
                }
            },


            // 下一步
            next(){
                // console.log('要提交的数据',this.autonymSubmitData)
                if( !this.id ){
                    if( !this.autonymSubmitData.qymc ){
                        uni.$u.toast('请选择所属企业')
                        return false
                    }
                    if( this.autonymSubmitData.__photo ){
                        uni.navigateTo({ url: '/pages/certification-bag/info-collect1' })
                    }else{
                        uni.$u.toast('请验证身份信息')
                    }
                }else{
                    uni.navigateTo({ url: '/pages/certification-bag/info-collect1' })
                }
            },


            // 删除已认证的人员
            getTest(){
                // 511025198805313878
                this.$request(this,this.$apis.autonymDelete,{zjhm:'513022199304143716',gcbh:this.userInfo.ssgcbh}).then(res=>{
                    console.log(res)
                }).then()
            },

            // 身份证人像照片验真(经过公安权威库) (可以得到身份证上的头像抠图)(暂未使用)
            // https://cloud.tencent.com/document/api/1007/47276
            getFaceidAuthSignature(face,ImageBase64){
                this.$request(this,this.$apis.faceidAuthSignature,{ImageBase64:ImageBase64}).then(res=>{
                    uni.showLoading({ title:'识别中' })
                    uni.request({
                        url: 'https://faceid.tencentcloudapi.com',
                        method: 'POST',
                        data:{
                            ImageBase64	: ImageBase64,
                        },
                        header: {
                            'X-TC-Action': 'CheckIdCardInformation',
                            'X-TC-Version': '2018-03-01',
                            'X-TC-Region': 'ap-beijing',
                            'X-TC-Timestamp': res.timestamp,
                            'Content-Type': 'application/json; charset=utf-8',
                            'Authorization': res.data,
                        },
                        success: e => {
                            uni.hideLoading()
                            if( e.data.Response.Error ){
                                uni.$u.toast('证件识别失败')
                            }else{
                                const result = e.data.Response
                                result.Portrait = 'data:image/jpeg;base64,'+result.Portrait
                                // // console.log('证件信息',result)
                                // 验证身份证是否已经存在 
                                this.autonymVerifyIdcard(ImageBase64,result)
                            }
                        },
                        fail: e => {
                            uni.hideLoading()
                            uni.$u.toast('证件识别失败')
                        }
                    });
                }).then()
            }
		}
	}
</script>

<style scoped lang="scss">
    .content{
        // 身份证照片上传
        /deep/.u-upload__button{
            margin: 0;
            border-radius: 8rpx;
            .u-icon__icon{
                font-size: 60rpx !important;
            }
            .u-upload__button__text{
                font-size: 24rpx;
            }
        }


        .item{
            background: $uni-text-color-inverse;
            box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.07);
        }
        .next-box{
            padding: 144rpx 0 70rpx;
            background: #FBFCFC;
            .next{
                width: 500rpx;
                margin: 0;
            }
        }
    }
</style>
